<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="">
          <el-input
            style="min-width: 230px"
            v-model="listQuery.name"
            placeholder="输入商品编号/名称/助记码"
            clearable
            size="small"
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleBatchDelete"
            >批量删除</el-button
          >
        </el-form-item>
      </el-form>
      <el-container>
        <el-aside width="218px">
          <el-tree
            :data="categories"
            :props="defaultProps"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            node-key="id"
          ></el-tree>
        </el-aside>
        <el-main>
          <el-table
            :data="datas"
            border
            v-loading="listLoading"
            fit
            highlight-current-row
            style="width: 100%"
            size="small"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column
              v-for="column in tableColumns"
              :key="column.key"
              :label="column.title"
              :prop="column.key"
              :align="column.align"
              :width="column.width ? column.width : ''"
            >
              <template slot-scope="scope">
                <div v-if="column.key == 'code'">
                  <el-link
                    :underline="false"
                    type="primary"
                    @click="handleEdit(scope)"
                    >{{ scope.row[column.key] }}</el-link
                  >
                </div>
                <div v-else>
                  {{ scope.row[column.key] }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleEdit(scope)"
                ></el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="handleDelete(scope)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.page_size"
            @pagination="getGoodsList"
          />
        </el-main>
      </el-container>
    </el-card>

    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="800px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品编号" prop="code">
              <el-input
                type="string"
                v-model="form.code"
                placeholder="商品编号"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="商品名称"
                clearable
                size="small"
                @input="getHanzi2Pinyin"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品类型" prop="cate">
              <el-cascader
                ref="cate"
                v-model="selectedKeys"
                :options="cates"
                :props="props"
                @change="handleChange"
                clearable
                size="small"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-select
                v-model="form.unit"
                placeholder="计量单位"
                size="small"
                clearable=""
              >
                <el-option
                  v-for="item in units"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="规格" prop="specs">
              <el-input
                type="string"
                v-model="form.specs"
                placeholder="规格"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input
                v-model="form.brand"
                placeholder="品牌"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产地" prop="place">
              <el-input
                type="string"
                v-model="form.place"
                placeholder="产地"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplier">
              <el-select
                v-model="form.supplier"
                placeholder="供应商"
                size="small"
                clearable
              >
                <el-option
                  v-for="item in suppliers"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购单价" prop="purchase_price">
              <el-input
                v-model="form.purchase_price"
                placeholder="采购单价"
                clearable
                size="small"
                @input="
                  form.purchase_price = form.purchase_price.replace(
                    /[^\d|.]/g,
                    ''
                  )
                "
              >
                <el-button slot="append">元</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售单价" prop="sale_price">
              <el-input
                v-model="form.sale_price"
                placeholder="销售单价"
                clearable
                size="small"
                @input="
                  form.sale_price = form.sale_price.replace(/[^\d|.]/g, '')
                "
              >
                <el-button slot="append">元</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="助记码" prop="help_code">
              <el-input
                type="string"
                v-model="form.help_code"
                placeholder="助记码"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条码" prop="bar_code">
              <el-input
                v-model="form.bar_code"
                placeholder="条码"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="会员折扣率" prop="discount">
              <el-input
                type="string"
                v-model="form.discount"
                placeholder="会员折扣率"
                clearable
                size="small"
              >
                <el-button slot="append">%</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="备注"
                clearable
                size="small"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(false)"
          >保存</el-button
        >
        <el-button type="primary" size="small" @click="handleSave(true)"
          >保存并新增</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { getParentsPath } from "@/utils/index";
import { mapGetters } from "vuex";
import {
  getGoods,
  addGoods,
  updateGoods,
  delGoods,
  delMultiGoods,
  getCategories,
  getUnitList,
  getSupplierList,
  getGoodsMaxCode,
  hanzi2pinyin,
} from "@/api/base";

const defaultForm = {
  id: null,
  code: "",
  name: "",
  cate: null,
  unit: null,
  bar_code: "",
  help_code: "",
  supplier: null,
  specs: "",
  brand: "",
  place: "",
  purchase_price: null,
  sale_price: null,
  discount: null,
  remark: null,
  user: null,
};

export default {
  name: "Goods",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        code: [
          {
            required: true,
            message: "请输入商品编号",
            trigger: "blur",
          },
        ],
        name: [
          {
            type: "string",
            required: true,
            message: "请输入商品名称",
            trigger: "blur",
          },
        ],
        cate: [
          {
            required: true,
            message: "请选择商品类型",
            trigger: "blur",
          },
        ],
        unit: [
          {
            required: true,
            message: "请选择计量单位",
            trigger: "blur",
          },
        ],
      },

      tableColumns: [
        {
          key: "code",
          title: "商品编号",
          width: "120",
        },
        {
          key: "name",
          title: "商品名称",
          width: "200",
        },
        {
          key: "cate_name",
          title: "商品分类",
          width: "120",
        },
        {
          key: "unit_name",
          title: "计量单位",
          width: "90",
        },
        {
          key: "specs",
          title: "规格",
          width: "120",
        },
        {
          key: "brand",
          title: "品牌",
          width: "100",
        },
        {
          key: "place",
          title: "产地",
          width: "120",
        },
        {
          key: "purchase_price",
          title: "采购单价",
          width: "100",
        },
        {
          key: "sale_price",
          title: "销售单价",
          width: "100",
        },
        {
          key: "stock_nums",
          title: "库存数量",
          width: "120",
        },
        {
          key: "discount",
          title: "会员折扣率%",
          width: "120",
        },
        {
          key: "bar_code",
          title: "条码",
        },
        {
          key: "supplier_name",
          title: "供应商",
          width: "120",
        },
        {
          key: "remark",
          title: "备注",
          width: "180",
        },
        {
          key: "user_name",
          title: "创建人",
        },
      ],

      title: "商品",
      dialogVisible: false,
      dialogType: "new",
      datas: [],
      categories: [],
      cates: [],
      units: [],
      suppliers: [],
      selectedKeys: [],
      selections: [],

      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: "",
        parent_id: null,
        cate_id: null,
      },
      //cascader
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      //tree
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getCategoryList();
    this.getGoodsList();
    this.getUnitList();
    this.getSupplierList();
  },
  methods: {
    getHanzi2Pinyin(){
      const params = {
        name: this.form.name
      }
      hanzi2pinyin(params).then(res=>{
        this.form.help_code = res.help_code
      })
    },
    getGoodsCode() {
      getGoodsMaxCode().then((res) => {
        console.log(res);
        this.form.code = res.max_code;
      });
    },
    getUnitList() {
      getUnitList().then((res) => {
        this.units = res;
      });
    },
    getSupplierList() {
      getSupplierList().then((res) => {
        this.suppliers = res;
      });
    },
    getCategoryList() {
      getCategories().then((res) => {
        console.log(res);
        this.cates = res;
        this.categories.push({ id: -1, name: "商品分类", children: res });
      });
    },
    getGoodsList() {
      this.listLoading = true;
      getGoods(this.listQuery)
        .then((res) => {
          this.datas = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          this.$message.error("获取数据失败!" + error);
          this.listLoading = false;
        });
    },
    //树形点击
    handleNodeClick(data) {
      console.log("handleNodeClick: ", data);
      if (data.children) {
        // 父类
        this.listQuery.parent_id = data.id;
        this.listQuery.cate_id = null;
      } else {
        this.listQuery.parent_id = null;
        this.listQuery.cate_id = data.id;
      }

      this.handleFilter();
    },

    handleChange(value) {
      console.log(value);
      if (this.selectedKeys.length > 0) {
        this.form.cate = this.selectedKeys[this.selectedKeys.length - 1];
      }
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getGoodsList();
    },
    // 增加f
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.getGoodsCode();

      this.dialogType = "new";
      this.dialogVisible = true;
      this.selectedKeys = [];
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改运营商
    handleEdit(scope) {
      this.form = scope.row;
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.selectedKeys = getParentsPath(this.form.cate, this.cates);
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delGoods(row.id);
          this.getGoodsList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message({
            type: "error",
            message: "删除失败!",
          });
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
      console.log(this.selections);
    },
    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delMultiGoods(sel_ids);
          this.getGoodsList();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";

        if (this.form.user == null) {
          this.form.user = this.uid;
        }

        let res = null;

        if (isEdit) {
          res = await updateGoods(this.form);
        } else {
          res = await addGoods(this.form);
        }

        this.getGoodsList();

        const { code, name, cate_name, unit_name } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
          this.getGoodsCode()
          this.form.cate = this.selectedKeys[this.selectedKeys.length - 1];
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>商品编号: ${code}</div>
              <div>商品名称: ${name}</div>
              <div>商品分类: ${cate_name}</div>
              <div>计量单位: ${unit_name}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.el-aside {
  .el-tree {
    border: 1px solid #eee;
    padding: 10px;
  }
}
.el-cascader,
.el-select {
  width: 100%;
}
.el-link {
  font-size: 12px;
}
</style>